'use strict';

import $store from './store'
import $config from './config'
import $common from "./common"
import _ from 'lodash'
import {
    wxLogin
} from 'common/api'

function service(options = {}) {
    // 获取接口token
    let token = uni.getStorageSync($config.__key_token) ?? ''
    if (options.url.indexOf('http') == -1) options.url = `${$config.apiUrl}${options.url}`
    options.header = {
        'Authorization': `${token}`
    }

    if (_.get(options, 'loadingText', '')) {
        uni.showLoading({
            title: options.loadingText
        })
    }

    return new Promise((resolved, rejected) => {
        options.success = (res) => {
            if (_.get(options, 'loadingText', '')) {
                uni.hideLoading()
            }

            let code = Number(res.data.code || res.statusCode)

            switch (code) {

                case -13:
                    miniAppLogin().then(res => {
                        let data = res.data
                        if (res.code == 200) {
                            $store.commit('login', data)
                            if (!data.needRegister && data.apiToken) {
                                service(options).then(r => {
                                    resolved(r);
                                })
                            }
                        }
                    })
                    break
                case 404:
                case 500:

                    uni.showModal({
                        title: '网络错误',
                        content: '网络开了小差，请刷新重试下哦~',
                        cancelText: '复制错误',
                        confirmText: '刷新页面',
                        success: (e) => {
                            if (e.cancel) {
                                let data = res.data ? (typeof res.data === 'string' ? res.data :
                                    JSON.stringify(res.data)) : null
                                $common.copyText(data)
                            }
                            if (e.confirm) {
                                $common.reloadPage()
                            }
                        },
                    });

                    break
                default:
                    if (!options.hideMsg && code != 200 && res.data.msg) {
                        $common.msg(res.data.msg, 3500)
                    }
                    resolved(res.data);
                    break
            }
        }
        options.fail = (err) => {
            uni.showToast({
                title: '网络异常请稍后再试',
                icon: 'none'
            })
            rejected(err)
        }
        uni.request(options)
    })
}

// 小程序登录
function miniAppLogin() {
    let promise = new Promise((resolve, reject) => {
        uni.getProvider({
            service: 'oauth',
            success: function (res) {
                console.log(res, 'resres')
                // 微信
                if (~res.provider.indexOf('weixin')) {
                    uni.login({
                        provider: 'weixin',
                        success: function (loginRes) {
                            wxLogin({
                                'code': loginRes.code
                            }).then(res => {
                                resolve(res);
                            })
                        },
                        fail: function (error) {
                            reject(error)
                        }
                    })
                }
            }
        })
    })
    return promise;

}

export default service